package com.car.advertising.util;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;

import com.support.widget.util.LogUtil;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import rx.functions.Action1;

/**
 * Created by zhenglei on 2017/4/1.
 * 调用系统相机、图库，
 * 兼容7.0
 */

public class CameraUtil {
    private File file;
    public static final int REQUEST_CAMERA = 111;
    public static final int REQUEST_PICTURE = 222;
    public static final int REQUEST_RESIZE = 333;
    private Uri imageUri;

    private Activity activity;
    private boolean needResize;
    private ResultCallback callback;


    public CameraUtil(Activity activity) {
        this.activity = activity;
    }

    /**
     * 调用相机拍照
     */
    public void openCamera(boolean needResize, ResultCallback callback, File saveFile) {
        this.file = saveFile;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //针对Android7.0，需要通过FileProvider封装过的路径，提供给外部调用
            imageUri = FileProvider.getUriForFile(activity, "com.car.advertising.fileprovider", file);//通过FileProvider创建一个content类型的Uri，进行封装
        } else { //7.0以下，如果直接拿到相机返回的intent值，拿到的则是拍照的原图大小，很容易发生OOM，所以我们同样将返回的地址，保存到指定路径，返回到Activity时，去指定路径获取，压缩图片
            imageUri = Uri.fromFile(file);
        }
        this.needResize = needResize;
        this.callback = callback;
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.request(android.Manifest.permission.CAMERA).subscribe(new Action1<Boolean>() {

            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent intent = new Intent();
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
                    LogUtil.e("第1步" + "第1步,调用相机拍照获取");
                    activity.startActivityForResult(intent, REQUEST_CAMERA);//启动拍照
                } else {
                    LogUtil.i("您已关闭相机权限，请到设置-权限管理中打开");
                }
            }
        });
    }

    /**
     * 从相册获取
     */
    public void openPicture(boolean needResize, ResultCallback callback, File saveFile) {
        this.file = saveFile;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //针对Android7.0，需要通过FileProvider封装过的路径，提供给外部调用
            imageUri = FileProvider.getUriForFile(activity, "com.car.advertising.fileprovider", file);//通过FileProvider创建一个content类型的Uri，进行封装
        } else { //7.0以下，如果直接拿到相机返回的intent值，拿到的则是拍照的原图大小，很容易发生OOM，所以我们同样将返回的地址，保存到指定路径，返回到Activity时，去指定路径获取，压缩图片
            imageUri = Uri.fromFile(file);
        }
        this.needResize = needResize;
        this.callback = callback;
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.request(android.Manifest.permission.CAMERA)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            try {
                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                LogUtil.e("第1步" + "第1步,开始从相册获取");
                                activity.startActivityForResult(intent, REQUEST_PICTURE);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            LogUtil.i("您已关闭相机权限，请到设置-权限管理中打开");
                        }
                    }
                });
    }


    public interface ResultCallback {
        void getResult(File saveFile);

        void onError(int code, String message);
    }

    public void onHandleActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (needResize) {
                    resizeImage(activity, imageUri);
                } else {
                    callback.getResult(file);
                }

                break;
            case REQUEST_PICTURE:
                if (data != null) {
                    imageUri = data.getData();
                    if (needResize) {
                        resizeImage(activity, imageUri);
                    } else {
                        file = new File(getRealPathFromURI(imageUri));
                        callback.getResult(file);
                    }
                }
                break;

            case REQUEST_RESIZE:
                if (data == null) {
                    callback.onError(1, "取消");
                    return;
                }

                Bundle extras = data.getExtras();
                if (extras == null) {
                    callback.onError(1, "取消");
                    return;
                }
                Bitmap bitmap = extras.getParcelable("data");
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    bitmap = null;
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                callback.getResult(file);
                break;
            default:

                break;
        }
    }


    /**
     * 裁剪图片
     */
    private void resizeImage(Activity activity, Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        // 图片格式
        intent.putExtra("outputFormat", "PNG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        LogUtil.e("第三步" + "第三步,开始裁剪");
        // 打开裁剪的activity,并且获取到裁剪图片(在第二步的RESIZE_REQUEST_CODE请求码中处理)
        activity.startActivityForResult(intent, REQUEST_RESIZE);
    }

    private String getRealPathFromURI(Uri contentUri) {
        String res = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.getContentResolver().query(contentUri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(column_index);
            }
            cursor.close();
        } else {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            res = cursor.getString(actual_image_column_index);
            cursor.close();
        }
        return res;
    }
}
